<template>
  <div class="app-container">
    <div
      v-show="
        !supplierInfo.visiable && !supplierProduct.visible && !orgInfos.visible
      "
    >
      <!-- 条件栏 -->
      <PageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-uploadFile>
          <el-upload
            :headers="uploadInfo.headers"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :before-upload="beforeUpload"
            :action="uploadInfo.action"
          >
            <el-button>导入模板</el-button>
          </el-upload>
        </template>
      </PageFilter>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="getMaintenancePage"
        :tab-index="true"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :check-box="false"
        :row-class-name="tableRowClassName"
      >
        <template v-slot:col-maintenanceName="scope">
          <span
            v-if="$permission('orgInfo:list')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.maintenanceName }}</span
          >
          <span v-else>{{ scope.row.maintenanceName }}</span>
        </template>
      </TableContainer>
    </div>
    <!-- 添加维保商 -->
    <SuppllierAdd
      v-if="supplierInfo.visiable"
      v-model:visible="supplierInfo.visiable"
      v-model:title="supplierInfo.title"
      @returnModify="search"
    />
    <SupplierProduct
      v-if="supplierProduct.visible"
      v-model:visible="supplierProduct.visible"
      :table-row="supplierProduct.data"
      @returnBack="getList"
      @callback="search"
    />
    <orgDetails
      v-if="orgInfos.visible"
      :id="orgInfos.id"
      v-model:visible="orgInfos.visible"
      @returnBack="getList"
    />
  </div>
</template>

<script setup name="maintenance">
import { getMaintenancePage, deleteMaintenance } from '@/api/core.js'
import SuppllierAdd from './detail/index'
import SupplierProduct from './supplierProduct'
import orgDetails from './detail/orgDetails'
import { exportTemplateExcel } from '@/api/pub'
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
const store = useStore()
const { proxy } = getCurrentInstance()
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/core/maintenanceProduct/import/excel',
  headers: {
    Authorization: store.state.user.token,
  },
  loading: {},
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    searchType: 'org',
    searchField: 'maintenanceId',
    sort: 'create_time desc,id asc',
  },
  list: [
    {
      type: 'button',
      label: '新增',
      show: proxy.$permission('maintenance:add'),
      event: add,
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
    },
    { type: 'slot', value: 'uploadFile' },
    {
      type: 'input',
      label: '名称/编码',
      value: 'keyword',
      event: search,
    },
    {
      type: 'select-model',
      label: '服务范围',
      value: 'serviceScope',
      checkDefault: false,
      code: 'service_scope',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [
    { label: '名称', value: 'maintenanceName', type: 'slot' },
    { label: '编码', value: 'maintenanceCode' },
    { label: '联系人', value: 'contact' },
    { label: '联系电话', value: 'contactNumber' },
    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
    { label: '服务范围', value: 'serviceScopeValue' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '140',
    btList: [
      {
        label: '关联装备',
        event: openSupplierProduct,
        show: proxy.$permission('maintenance:product'),
      },
      {
        label: '解除关系',
        event: disengagement,
        show: proxy.$permission('maintenance:relieve'),
      },
      // TODO: 2020.5.22 解除关系功能暂时不上
    ],
  },
})
// 表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '名称', value: 'name', type: 'input', required: true },
    { label: '编码', value: 'code', type: 'input', required: true },
  ],
  rules: {},
  labelWidth: '100px',
})
const supplierInfo = ref({
  visiable: false,
  title: '新增维保商',
})
const supplierProduct = ref({
  visible: false,
  data: {},
})
const orgInfos = ref({
  visible: false,
  id: '',
})

// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 添加
function add() {
  supplierInfo.value.visiable = true
}
// 解除关系
function disengagement(data) {
  let ids = [data.id]
  proxy
    .$confirm(
      `解除关系将清空与【${data.maintenanceName}】绑定的所有产品，确认解除关系吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      deleteMaintenance(ids).then((resp) => {
        if (resp && resp.success) {
          tableInfo.value.initCurpage = Math.random()
          tableInfo.value.refresh = Math.random()
        }
      })
    })
}
//打开维保商产品界面
function openSupplierProduct(row) {
  console.log(row)
  sessionStorage.setItem('storeRowId', row.id)
  supplierProduct.value.visible = true
  supplierProduct.value.data = { ...row }
}
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  orgInfos.value.id = row.maintenanceId
  orgInfos.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function downloadTemplate() {
  exportTemplateExcel('core_maintenance_product_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function beforeUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function uploadSuccess(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}

onMounted(() => {
  getList()
})
</script>

<style scoped></style>
